<?php

namespace App\Http\Controllers\Api\V1;

use App\Models\User;
use App\Models\GoldProduct;
use App\Jobs\CloseGoldRecordJob;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Facades\Cache;
use App\Jobs\ApplyGoldProductOrderJob;
use App\Jobs\ApplyGoldProductSplitJob;
use App\Services\MakeGoldRecord\MakeGoldRecordRequest;
use App\Services\ApplyGoldRecordBatchPay\ApplyGoldRecordBatchPay;
use App\Services\ApplyGoldProductOrder\ApplyGoldProductOrderRequest;
use App\Services\ApplyGoldProductSplit\ApplyGoldProductSplitRequest;
use App\Services\ApplyGoldRecordBatchPay\ApplyGoldRecordBatchPayRequest;
use App\Services\ApplyGoldProductReselling\ApplyGoldProductBatchReselling;
use App\Services\ApplyGoldProductReselling\ApplyGoldProductBatchResellingRequest;
use App\Services\ApplyGoldRecordUploadVoucher\ApplyGoldRecordUploadVoucherRequest;
use App\Services\ApplyGoldRecordUploadVoucher\ApplyGoldRecordUploadVoucher;
use App\Services\ApplyGoldRecordBatchExamine\ApplyGoldRecordBatchExamineRequest;
use App\Services\ApplyGoldRecordBatchExamine\ApplyGoldRecordBatchExamine;
use App\Services\ApplyGoldRecordContact\ApplyGoldRecordContactRequest;
use App\Services\ApplyGoldRecordContact\ApplyGoldRecordContact;
use App\Services\ApplyGoldRecordBatchPay\ApplyGoldRecordBatchPayByAlipayRequest;
use Rainsens\Dinglog\Facades\Dinglog;
use Illuminate\Support\Facades\Redis;




class GoldRecordsController extends Controller
{
	public function __construct()
	{
        /*$routeAction = explode('@', Route::currentRouteAction());
        if ($user = request()->user() and $routeAction[1] == 'store') {
            $user->setStormClick();
        }*/
		$this->middleware('random.drop.storm:50')->only('store');
	}

	public function index(): JsonResponse
	{
		/**
		 * @var User $user
		 */
		$user = request()->user();

		$condition = request('condition');
		$fromIndex = (int)request('index', 0);
		$records = $user->myRecordsCachePage($condition, $fromIndex);

		return response()->json($records);
	}

	public function voucherList(): JsonResponse
	{
		/**
		 * @var User $user
		 */
		$user = request()->user();

		$record = request('record');
		$records = $user->myRecordsVoucherCachePage($record);

		return response()->json($records);
	}


	public function examineCount(): JsonResponse
	{
		/**
		 * @var User $user
		 */
		$user = request()->user();

		return response()->json(['count'=>$user->myRecordsExamineCacheCount()]);
	}

	public function count(): JsonResponse
	{
		/**
		 * @var User $user
		 */
		$user = request()->user();

		return response()->json($user->myRecordsCacheCount());
	}

	public function counts(): JsonResponse
	{
		$user = request()->user();
		$counts = $user->myRecordsCacheCount();
		$money = $user->getUnpaidRecordCacheAllMoney();
		$totalCount =$counts['unpaid'] + $counts['pending'] + $counts['running'];
		return response()->json(['counts' => $counts,'money'=> $money,'total_count'=>$totalCount,'pay_expire_minuts'=>sc('pay_gold_record_must_within_minutes')]);
	}

	public function store()
	{
		$lock = Cache::lock('buy_gold_product', 15);

		try {

			// if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(MakeGoldRecordRequest::class);
			$uid = $request->user()->id;
			$pid = $request->pid;
			$rid = $request->rid;


			if (! GoldProduct::sIsInSoldCache($pid, $rid)) {

				$item = GoldProduct::sGetCache($pid, $rid);
				$user = request()->user();
				$user->setGoldBeans($item['gold_beans_today']);
				GoldProduct::sBuyFromCache($uid, $pid, $rid);
			}

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}


	public function voucher()
	{
		$lock = Cache::lock('upload_gold_product_voucher', 15);

		try {

			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldRecordUploadVoucherRequest::class);

			app(ApplyGoldRecordUploadVoucher::class, [
				'user' => $request->user(),
				'unpaidCacheId' => $request->record,
				'voucher' => $request->voucher,
			])->upload();

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}

	public function batchExamine()
	{
		$lock = Cache::lock('batch_examine_gold_product', 15);

		try {
			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldRecordBatchExamineRequest::class);
			
			app(ApplyGoldRecordBatchExamine::class, [
				'user' => $request->user(),
				'unpaidCacheIds' => $request->getUnpaidCacheIds(),
				'examineRecord' => $request->examine_record,
			])->examine();

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}


	public function batchPay()
	{
		$lock = Cache::lock('batch_pay_gold_product', 15);

		try {
			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldRecordBatchPayRequest::class);
			
			app(ApplyGoldRecordBatchPay::class, [
				'user' => $request->user(),
				'unpaidCacheIds' => $request->getUnpaidCacheIds(),
				'method' => 'balance'
			])->pay();

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}


	public function batchPayByAlipay()
	{
		$lock = Cache::lock('batch_pay_gold_product', 15);
		$alipay = cs("storm")->is_alipay_open;
		if(empty($alipay)){

			fail('支付宝支付暂不可用');
		}
		try {
			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldRecordBatchPayByAlipayRequest::class);
			
			$result  = app(ApplyGoldRecordBatchPay::class, [
				'user' => $request->user(),
				'unpaidCacheIds' => $request->getUnpaidCacheIds(),
				'method' => 'alipay'
			])->pay();

            return response()->json(['result' => $result, 'cache_ids' => request('records')]);
            
		} finally {
			$lock->release();
		}
	}


	public function batchPayByWxpay()
	{
		$lock = Cache::lock('batch_pay_gold_product', 15);
		$wxpay = cs("storm")->is_wxpay_open;
		if(empty($wxpay)){

			fail('微信支付暂不可用');
		}
		try {
			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldRecordBatchPayByAlipayRequest::class);
			
			$result  = app(ApplyGoldRecordBatchPay::class, [
				'user' => $request->user(),
				'unpaidCacheIds' => $request->getUnpaidCacheIds(),
				'method' => 'wxpay'
			])->pay();

            return response()->json(['result' => $result, 'cache_ids' => request('records')]);
            
		} finally {
			$lock->release();
		}
	}

	public function batchResell()
	{
		$lock = Cache::lock('batch_resell_gold_product', 15);

		try {
			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldProductBatchResellingRequest::class);

			app(ApplyGoldProductBatchReselling::class, [
				'user' => $request->user(),
				'pendingCacheIds' => $request->getPendingCacheIds()
			])->apply();

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}

	public function split()
	{
		$lock = Cache::lock('split_gold_product', 15);

		try {

			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldProductSplitRequest::class);

			/**
			 * @var User $user
			 */
			$user = $request->user();

			$cacheId = $request->record;

			$user->markRecordCacheSpliting($cacheId);
			$queue = app()->environment('local') ? 'default' : 'default';
			dispatch(new ApplyGoldProductSplitJob($user, $cacheId))->onQueue($queue);

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}

	public function take()
	{
		$lock = Cache::lock('take_gold_product', 15);

		try {

			if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldProductOrderRequest::class);

            /**
             * @var User $user
             */
			$user = $request->user();
			$cacheId = $request->record;
			$address = $request->getAddress();

			$user->markRecordCacheTaking($cacheId);
			$queue = app()->environment('local') ? 'default' : 'default';
			dispatch(new ApplyGoldProductOrderJob($user, $cacheId, $address))->onQueue($queue);

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}

	public function contact()
	{
		$lock = Cache::lock('contact_gold_product', 15);

		try {

			//if (! $lock->get()) fail('高峰拥挤，请再试');

			$request = app(ApplyGoldRecordContactRequest::class);

            /**
             * @var User $user
             */
			app(ApplyGoldRecordContact::class, [
				'user' => $request->user(),
				'unpaidCacheId' => $request->record,
			])->upload();

            return response(null, 204);

		} finally {
			$lock->release();
		}
	}

	 public function config()
    {
	    /**
	     * @var User $user
	     */
	    $config=[
	    	'is_alipay_open'=>cs("storm")->is_alipay_open,
	    	'is_wxpay_open'=>cs("storm")->is_wxpay_open,
	    ]; 
	     return response()->json($config);
    }
}
